home *** CD-ROM | disk | FTP | other *** search
- Path: news.mcs.net!not-for-mail
- From: supercat@MCS.COM (John Payson)
- Newsgroups: comp.arch.embedded,comp.lang.c
- Subject: Re: Using malloc of C on embedded system?
- Date: 1 Apr 1996 00:52:38 -0600
- Organization: /usr/lib/news/organi[sz]ation
- Message-ID: <4jnufm$lr1@Mercury.mcs.com>
- References: <4jml7h$cbc@castor.usc.edu>
- NNTP-Posting-Host: mercury.mcs.com
-
- In article <4jml7h$cbc@castor.usc.edu>,
- Stannon Yen <chuitiny@castor.usc.edu> wrote:
- >Hello,
- >
- > This is just a general question. Is it possible to use C function
- >malloc and free on system that has no OS? How can I setup the memory
- >pool for dynamic allocation/deallocation of memory?
- >
- > Any help is welcome.
-
- If your C library does not already provide a malloc/free function pair, your
- best bet is probably to declare an array which uses up all available memory,
- and then allocate stuff out of that.
-
- As to how complex you make your malloc/free functions, that depends in
- large measure upon what you need to do with them. For example, one really
- easy approach is:
-
- static char memory_data[MEM_SIZE];
- static char *mem_end;
-
- void initmem(void)
- {
- mem_end = memory_data;
- }
-
- void *malloc(int size)
- {
- char *temp = mem_end;
- mem_end += size;
- return (void*) temp;
- }
-
- void free(void *ptr)
- {
- /* Don't bother to free anything--if programs need to start over, they
- can re-invoke initmem */
- }
-
- As you can see, this approach is very easy and--in many embedded systems--
- quite adequate. If it's important that "free" actually DOES something,
- you should consider carefully the what size pieces you'll be malloc'ing
- and free'ing and what this could do to memory fragmentation. If the sizes
- of the things you'll be allocating tend to be powers of two, I'd highly
- suggest looking at a "binary buddy" system; they require little overhead,
- offer O(lg(n)) alloc/release, and tend to be relatively immune to external
- fragmentation.
-
- --
- -------------------------------------------------------------------------------
- supercat@mcs.com | "Je crois que je ne vais jamais voir... | J\_/L
- John Payson | Un animal aussi beau qu'un chat." | ( o o )
-